package com.gy.controller.result;

import com.alibaba.excel.EasyExcel;
import com.gy.config.BaiduOcrConfig;
import com.gy.controller.assistant.utils.PdfExtractUtil;
import com.gy.controller.common.UserHolder;
import com.gy.entity.Export.CustomCellWriteHandler;
import com.gy.entity.Export.ExportField;
import com.gy.entity.Export.ExportRequest;
import com.gy.entity.result.ContinueEducationMaterial;
import com.gy.entity.result.PersonalAward;
import com.gy.entity.result.Publication;
import com.gy.query.ContinueEducationMaterialQuery;
import com.gy.query.PublicationQuery;
import com.gy.result.Result;
import com.gy.service.PublicationService;
import com.gy.vo.PageVO;
import com.gy.vo.summary.PublicationVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/publication")
@Api(tags = "著作接口")
@CrossOrigin
public class PublicationController {
    @Autowired
    private PublicationService publicationService;

    @Autowired
    private BaiduOcrConfig baiduOcrConfig; // 百度OCR工具类（与工具类一致）
    @Autowired
    private PdfExtractUtil pdfExtractUtil;
    /**
     * 根据openid分页查看某个人的著作信息
     */
    @PostMapping("/get/publication")
    @ApiOperation("根据openid查看某个人的著作材料")
    public Result<PageVO<Publication>> getPapers(@RequestBody PublicationQuery publicationQuery){
        return publicationService.getPublication(publicationQuery);
    }

    /**
     * 根据id主键删除著作
     */
    @DeleteMapping("/deleteById/{id}")
    @ApiOperation("根据id主键删除著作")
    public Result deleteById(@PathVariable Long id){
        return publicationService.removePublication(id);
    }

    /**
     * 根据id主键查看著作
     */
    @GetMapping("/getPublicationById/{id}")
    @ApiOperation("根据id主键查看著作")
    public Result getPublicationById(@PathVariable Long id){
        return Result.success(publicationService.getPublicationById(id));
    }

    /**
     * 更改著作
     */
    @PutMapping("/update")
    @ApiOperation("更改著作")
    public Result update(@RequestBody Publication publication){
        return publicationService.updatePublication(publication);
    }

    /**
     * 新增著作
     */
    @PostMapping("/save")
    @ApiOperation("新增著作")
    public Result save(@RequestBody Publication publication){
        return publicationService.savePublication(publication);
    }

    /**
     * 根据多个id查询著作
     */
    @PostMapping("/getByIds")
    @ApiOperation("根据多个id查询著作")
    public Result getByIds(@RequestBody Long[] ids){
        return publicationService.getPublicationBatchIds(ids);
    }

    /**
     * excel批量导出
     */
    @PostMapping("/export")
    @ApiOperation("excel批量导出")
    public void exportPersonalAward(@RequestBody ExportRequest request, HttpServletResponse response) throws IOException {
        List<ExportField> fields = request.getFields();
        List<Map<String, Object>> data = request.getData();

        String fileName = "exported_Publication.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

        // 动态生成表头
        List<List<String>> head = fields.stream()
                .map(field -> Arrays.asList(field.getLabel()))
                .collect(Collectors.toList());

        // 将 Map<String, Object> 转换为 List<List<Object>>
        List<List<Object>> transformedData = data.stream()
                .map(map -> fields.stream()
                        .map(field -> map.get(field.getKey()))
                        .collect(Collectors.toList()))
                .collect(Collectors.toList());

        // 写入数据
        EasyExcel.write(response.getOutputStream())
                .head(head)
                .registerWriteHandler(new CustomCellWriteHandler(fields))
                .sheet("Publication")
                .doWrite(transformedData);
    }

    /**
     * 获取著作汇总信息
     */
    @GetMapping("/getSummary")
    @ApiOperation("获取著作汇总信息")
    public Result<List<PublicationVO>> getSummary() {
        Long userId = UserHolder.getUser().getUserId();
        if (userId == null) {
            return Result.error("用户未登录或信息异常");
        }

        // 查询著作信息，并映射到 PublicationVO
        List<Publication> publicationList = publicationService.lambdaQuery()
                .eq(Publication::getUserId, userId)
                .select(
                        Publication::getTitle,
                        Publication::getAuthorRank,
                        Publication::getRole,
                        Publication::getPublisher,
                        Publication::getType,
                        Publication::getPublishDate,
                        Publication::getIsbn,
                        Publication::getLocation,
                        Publication::getWordCount
                )
                .list();

        // 数据转换，映射到 PublicationVO
        List<PublicationVO> publicationVOList = publicationList.stream()
                .map(pub -> PublicationVO.builder()
                        .title(pub.getTitle())
                        .authorRank(pub.getAuthorRank())
                        .role(pub.getRole())
                        .publisher(pub.getPublisher())
                        .type(pub.getType())
                        .publishDate(pub.getPublishDate())
                        .isbn(pub.getIsbn())
                        .location(pub.getLocation())
                        .wordCount(pub.getWordCount())
                        .build())
                .collect(Collectors.toList());

        return Result.success(publicationVOList);
    }

    /**
     * 新增：著作文件解析接口
     * 功能：上传PDF后自动提取字段，返回给前端填充表单
     * @param request 含filePath（PDF转图片的imageBasePath）、pdfPath（原始PDF路径）
     * @return 解析后的Publication + 原始OCR文本
     */
    @PostMapping("/parse")
    public Result<Map<String, Object>> parsePublication(@RequestBody Map<String, String> request) {
        try {
            String filePath = request.get("filePath"); // PDF转图片的路径（用于OCR）
            String pdfPath = request.get("pdfPath");   // 原始PDF文件路径（关联实体）

            // 1. 校验参数
            if (filePath == null || filePath.trim().isEmpty()) {
                return Result.error("著作图片路径不能为空");
            }
            if (pdfPath == null || pdfPath.trim().isEmpty()) {
                return Result.error("著作PDF文件路径不能为空");
            }

            // 2. 提取OCR文本（著作取前3页：封面+版权页+目录页，含核心信息）
            String ocrText = pdfExtractUtil.extractPdfTextFromImages(filePath, baiduOcrConfig);
            if (ocrText == null || ocrText.trim().isEmpty()) {
                return Result.error("OCR识别失败，未提取到文本");
            }

            // 3. AI解析著作字段（调用工具类新增方法）
            Publication publication = pdfExtractUtil.extractPublicationByAi(ocrText, pdfPath);

            // 4. 返回结果给前端（用于填充表单）
            return Result.success(Map.of(
                    "publication", publication, // 解析后的著作数据
                    "rawOcrText", ocrText     // 原始OCR文本（调试用）
            ));

        } catch (Exception e) {
            log.error("著作解析失败", e);
            return Result.error("解析失败：" + e.getMessage());
        }
    }

}
